import base64
import json
from json import JSONDecodeError

from locust import task, FastHttpUser, constant, tag, run_single_user, SequentialTaskSet


def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')


def decode64_str(data):
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str



class LoginTask(FastHttpUser):
    # wait_time = constant(1)
    host = "https://www.retone-hearing.fit"
    header = {"Content-Type": "application/json"}

    # count_task = 0
    @task(1)
    @tag('login')
    def login(self):
        login_url = '/microServiceUser/responseEncode/requestDecode/login'
        info = {
            "type": 0,
            "sourcePlatform": "RETONE_FIT",
            "password": "cc1234",
            "loginObject": "pertester"
        }
        with self.rest('post', login_url, data=enconde_bs64(info)) as resp:
            try:
                if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()['description'] != None):
                    resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
                else:
                    # print(resp.json())
                    resp.success()
            except JSONDecodeError:
                resp.failure("Response could not be decoded as JSON")
            except KeyError:
                resp.failure("Response did not contain expected key 'data'")


if __name__ == '__main__':
    # os.system('locust -f stress_login.py --web-host="127.0.0.1"')
    run_single_user(LoginTask)
